import {ref} from "vue"
import io from "socket.io-client"; //引入socket.io-client

import LocalCache from "./cache"

var socket = ''
var usertoken = ''
const usesocket = (id)=>{
    let userid = LocalCache.getCache('id')
    if (socket == '' && usertoken == '') {
        socket = io.connect("ws://127.0.0.1:3000");
        console.log(id);
        usertoken = id
        socket.emit('bainduserid',{usertoken,userid})
    } else if(usertoken != id) {
        usertoken = id
        socket.emit('bainduserid',{usertoken,userid})
    }
    return socket
}

const onsocket = (store,userid)=>{
    console.log(socket);
    //聊天的对象id 
    console.log(userid);
    socket.on('connect',()=>{
        console.log("lianjie");
    })
    //监听 客户端传来的消息 
    socket.on("pushMsg",(data)=>{
        if (data.id !=socket.id ) {
            data.type = 1 
            store.dispatch("ws/setmessagedata",data)
        }
    })
    socket.on("msg",(data)=>{
        store.commit('ws/setmessagedata',data)
    })
    //用户在线 列表 
  socket.on("online",(userlist)=>{
    store.commit("ws/setonlinelists",userlist)
  })
    const sendclick = () => {
        const message = {
          message: sendmessage.value,
          type: 0,
          wsid:socket.id,
          userid:usertoken
        };
        store.dispatch("ws/setmessagedata",message)
        socket.emit("sendMsg", message);
        sendmessage.value = "";
      };
      const sendmessage = ref()
    return { sendclick ,sendmessage}

}
export { onsocket ,usesocket }